<template>
  <div class="leave-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>请假申请</span>
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio-button label="申请">申请请假</el-radio-button>
            <el-radio-button label="记录">申请记录</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <!-- 请假申请表单 -->
      <div v-if="activeTab === '申请'">
        <el-button type="primary" @click="showLeaveForm = true">新建请假</el-button>
        
        <el-dialog v-model="showLeaveForm" title="新建请假申请" width="650px">
          <el-form ref="leaveFormRef" :model="leaveForm" :rules="leaveRules" label-width="100px">
            <el-form-item label="请假类型" prop="type">
              <el-select v-model="leaveForm.type" placeholder="请选择请假类型" style="width: 100%">
                <el-option label="事假" value="事假" />
                <el-option label="病假" value="病假" />
                <el-option label="婚假" value="婚假" />
                <el-option label="丧假" value="丧假" />
                <el-option label="产假" value="产假" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker 
                v-model="leaveForm.startTime" 
                type="datetime" 
                placeholder="选择开始时间" 
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker 
                v-model="leaveForm.endTime" 
                type="datetime" 
                placeholder="选择结束时间" 
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="请假原因" prop="reason">
              <el-input 
                v-model="leaveForm.reason" 
                type="textarea" 
                :rows="4" 
                placeholder="请详细说明请假原因"
              />
            </el-form-item>
            
            <el-form-item label="证明材料">
              <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :on-change="handleFileChange"
                :limit="3"
                multiple
              >
                <template #trigger>
                  <el-button type="primary">选择文件</el-button>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传PDF、JPG或PNG格式文件，最大不超过10MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showLeaveForm = false">取消</el-button>
              <el-button type="primary" @click="submitLeave">提交申请</el-button>
            </span>
          </template>
        </el-dialog>
        
        <div class="empty-tip" v-if="!hasSubmitted">
          <el-empty description="暂无进行中的请假申请" />
        </div>
        
        <div v-else class="approval-path">
          <h3>当前申请审批路径</h3>
          <el-steps :active="activeStep" finish-status="success" align-center>
            <el-step title="提交申请" description="已于2023-05-10 09:15提交" />
            <el-step title="辅导员审批" description="王老师 - 审批中" />
            <el-step title="院系审批" description="教务处" />
            <el-step title="生成请假单" description="自动生成带电子签章请假单" />
          </el-steps>
        </div>
      </div>
      
      <!-- 申请记录列表 -->
      <div v-else>
        <el-table :data="leaveRecords" style="width: 100%">
          <el-table-column prop="id" label="申请编号" width="100" />
          <el-table-column prop="type" label="请假类型" width="100" />
          <el-table-column prop="startTime" label="开始时间" width="160" />
          <el-table-column prop="endTime" label="结束时间" width="160" />
          <el-table-column prop="duration" label="请假时长" width="100" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag 
                :type="getStatusType(scope.row.status)" 
                effect="plain"
              >
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button 
                link 
                type="primary" 
                @click="viewLeaveDetail(scope.row)"
              >
                查看详情
              </el-button>
              <el-button 
                v-if="scope.row.status === '已批准'"
                link 
                type="success" 
                @click="downloadLeaveForm(scope.row)"
              >
                下载请假单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="请假详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请编号">{{ currentLeave.id }}</el-descriptions-item>
        <el-descriptions-item label="请假类型">{{ currentLeave.type }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentLeave.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentLeave.endTime }}</el-descriptions-item>
        <el-descriptions-item label="请假时长">{{ currentLeave.duration }}</el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag :type="getStatusType(currentLeave.status)">{{ currentLeave.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请假原因" :span="2">
          {{ currentLeave.reason }}
        </el-descriptions-item>
        <el-descriptions-item label="审批记录" :span="2">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in currentLeave.approvalLog"
              :key="index"
              :type="activity.type"
              :color="activity.color"
              :timestamp="activity.timestamp"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Download } from '@element-plus/icons-vue'
import studentApi from '@/api/modules/student'

// 当前活动标签
const activeTab = ref('申请')

// 请假表单显示控制
const showLeaveForm = ref(false)
const leaveFormRef = ref(null)

// 请假表单数据
const leaveForm = reactive({
  type: '',
  startTime: '',
  endTime: '',
  reason: '',
  files: []
})

// 表单验证规则
const leaveRules = {
  type: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  reason: [{ required: true, message: '请填写请假原因', trigger: 'blur' }]
}

// 是否已提交请假申请
const hasSubmitted = ref(false)
const activeStep = ref(1)

// 请假记录数据
const leaveRecords = ref([])

// 当前查看的请假详情
const showDetailDialog = ref(false)
const currentLeave = ref({})

// 处理文件上传
const handleFileChange = (file) => {
  console.log('选择文件:', file)
}

// 提交请假申请
const submitLeave = () => {
  leaveFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里可以添加实际的提交逻辑
      ElMessageBox.confirm(
        '确认提交此次请假申请吗？',
        '提交确认',
        {
          confirmButtonText: '确认提交',
          cancelButtonText: '取消',
          type: 'info',
        }
      )
        .then(async () => {
          try {
            // 提交请假申请
            const res = await studentApi.submitLeave({
              type: leaveForm.type,
              startTime: leaveForm.startTime,
              endTime: leaveForm.endTime,
              reason: leaveForm.reason,
              files: leaveForm.files
            })
            
            if (res.code === 200) {
              ElMessage({
                type: 'success',
                message: '请假申请已提交',
              })
              showLeaveForm.value = false
              hasSubmitted.value = true
              
              // 重置表单
              leaveFormRef.value.resetFields()
              
              // 刷新请假记录
              fetchLeaveList()
            }
          } catch (error) {
            console.error('提交请假申请失败:', error)
            ElMessage.error('提交请假申请失败')
          }
        })
        .catch(() => {
          // 用户取消提交
        })
    } else {
      return false
    }
  })
}

// 查看请假详情
const viewLeaveDetail = (row) => {
  currentLeave.value = row
  showDetailDialog.value = true
}

// 下载请假单
const downloadLeaveForm = (row) => {
  ElMessage({
    type: 'success',
    message: `请假单 ${row.id} 下载成功`,
  })
}

// 根据状态获取标签类型
const getStatusType = (status) => {
  const types = {
    '审批中': 'info',
    '已批准': 'success',
    '已驳回': 'danger',
    '已取消': 'warning'
  }
  return types[status] || 'info'
}

// 处理标签切换
const handleTabChange = (val) => {
  console.log('切换到标签:', val)
}

const fetchLeaveList = async () => {
  try {
    const res = await studentApi.getLeaveList()
    if (res.code === 200 && res.data) {
      leaveRecords.value = res.data
    }
  } catch (error) {
    console.error('获取请假记录失败:', error)
    ElMessage.error('获取请假记录失败')
  }
}

onMounted(() => {
  fetchLeaveList()
})
</script>

<style scoped>
.leave-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-tip {
  margin-top: 40px;
  text-align: center;
}

.approval-path {
  margin-top: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.approval-path h3 {
  margin-bottom: 20px;
  color: #303133;
}
</style> 